import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:proj_sfv/component/Chat.dart';
import 'package:proj_sfv/component/MyNotification.dart';
import 'package:proj_sfv/domain/UserDetail.dart';
import 'package:proj_sfv/http/api.dart';
import 'package:proj_sfv/http/requests.dart';
import 'package:proj_sfv/pages/UserVoListPage.dart';
import 'package:tencent_cloud_chat_uikit/business_logic/view_models/tui_friendship_view_model.dart';
import 'package:tencent_cloud_chat_uikit/data_services/conversation/conversation_services.dart';
import 'package:tencent_cloud_chat_uikit/data_services/services_locatar.dart';
import 'package:tencent_cloud_chat_uikit/tencent_cloud_chat_uikit.dart';
import 'package:tencent_cloud_chat_uikit/ui/controller/tim_uikit_conversation_controller.dart';

class UserDetailsPage2 extends StatefulWidget {
  final int userId;
  final String token;
  final int myId;

  UserDetailsPage2(this.userId, this.token, this.myId);

  @override
  _UserDetailsPageState createState() => _UserDetailsPageState();
}

class _UserDetailsPageState extends State<UserDetailsPage2> {

  UserDetail _detail = UserDetail.empty();
  bool _isFollowing = false;
  bool _isFriend = false;
  bool _isBlockedFriend = false;
  final ConversationService _conversationService = serviceLocator<ConversationService>();
  final TIMUIKitConversationController _controller = TIMUIKitConversationController();

  @override
  void initState() {
    getUserDetailInfoRequest(context, widget.token, widget.userId).then((value) {
      setState(() {
        _detail = value;
      });
    });
    getUserRelationRequest(context, widget.myId, widget.token, widget.userId).then((value) {
      setState(() {
        _isFriend = value[0];
        _isFollowing = value[1];
        _isBlockedFriend = value[2];
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final manager = TencentImSDKPlugin.v2TIMManager.getFriendshipManager();
    var conversationManager = TencentImSDKPlugin.v2TIMManager.getConversationManager();
    TUIFriendShipViewModel model = serviceLocator<TUIFriendShipViewModel>();
    return Scaffold(
      appBar: AppBar(
        title: Text("用户详情"),
      ),
      body: Column(
        children: [
        // User profile image and username
        Expanded(
          child: Column(
            children: [
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  CircleAvatar(
                    backgroundImage: NetworkImage(_detail.profile),
                    radius: 80,
                  ),
                  SizedBox(width: 16),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          _detail.userName,
                          style: TextStyle(
                            fontSize: 20,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        Text(_detail.signature),
                      ],
                    ),
                  ),
                ],
              ),
              // Gender and address
              SizedBox(height: 30,),
              Align(
                alignment: Alignment.centerLeft ,
                child: Padding(
                  padding: const EdgeInsets.only(left: 20),
                  child: Column(
                    children: [
                      Text(
                        _detail.gender == true ? '男' : '女',
                        style: TextStyle(fontSize: 16),
                        textAlign: TextAlign.left,
                      ),
                      Text(_detail.currentAddress, textAlign: TextAlign.left,),
                    ],
                  ),
                ),
              ),
              SizedBox(height: 30,),
              Divider(height: 2,),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: Row(
                  children: [
                    _buildCountWidget(_detail.followsCount, "关注", "$getFollowed${widget.userId}"),
                    _buildCountWidget(_detail.fansCount, "粉丝", "$getFans${widget.userId}"),
                    // _buildCountWidget(_detail.likeCount, "喜爱"),
                  ],
                ),
              ),
            ],
          ),
        ),
        Padding(
          padding: EdgeInsets.only(bottom: 20, left: 6, right: 6),
          child: Column(
            children: [
              Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              mainAxisSize: MainAxisSize.max,
              children: [
                ElevatedButton(
                  onPressed: () async {
                    if (!_isFollowing) {
                      var result = await followUserRequest(context, widget.myId, widget.token, widget.userId);
                      if (result != null) {
                        Fluttertoast.showToast(msg: "关注${_detail.userName}成功");
                        setState(() {
                          _isFollowing = !_isFollowing;
                          _detail.fansCount++;
                        });
                      }
                    } else {
                      String value = await showDialog<String>(context: context, builder: (BuildContext build) =>
                          MyNotification("确认要取消关注${_detail.userName}吗", [
                            ElevatedButton(onPressed: () async {
                              var result = unfollowUserRequest(context, widget.myId, widget.token, widget.userId);
                              if (result != null) {
                                Fluttertoast.showToast(msg: "取消关注成功");
                                Navigator.pop(context, "success");
                              } else {
                                Navigator.pop(context, "failed");
                              }
                            }, child: Text("确认")),
                            ElevatedButton(onPressed: () => Navigator.pop(context, "cancel"), child: Text("取消"))
                          ]));
                      if (value == "success") {
                        Fluttertoast.showToast(msg: "取消关注成功");
                        setState(() {
                          _detail.fansCount--;
                          _isFollowing = false;
                        });
                      }
                    }
                  },
                  child: Text(_isFollowing ? "取消关注" : "关注"),
                ),
                SizedBox(width: 16),
                ElevatedButton(
                  onPressed: () async {
                    if (_isFriend) {
                      // 删除好友
                      String value = await showDialog<String>(context: context, builder: (BuildContext build) =>
                          MyNotification("是否删除好友${_detail.userName}?", [
                            ElevatedButton(onPressed: () async {
                              var result = await addFriendRequest(context, widget.myId, widget.token,
                                  widget.userId, meg: FRIEND_RELATION_MEG.DEL);
                              if (result != null) {
                               var result2 = await manager.deleteFromFriendList(userIDList: [widget.userId.toString()],
                                   deleteType: FriendTypeEnum.V2TIM_FRIEND_TYPE_BOTH);
                               // 删除指定会话
                               var result3 = await conversationManager.deleteConversation(conversationID: "c2c_${widget.userId}");
                               _controller.loadData();
                                if (result2.code == 0 && result3.code == 0) {
                                  Fluttertoast.showToast(msg: "删除好友成功");
                                  model.loadData(); // 更新好友列表
                                  Navigator.pop(context, "success");
                                } else {
                                  Navigator.pop(context, "failed");
                                }
                              }
                            }, child: Text('确认')),
                            ElevatedButton(onPressed: () => Navigator.pop(context, "cancel"), child: Text("取消"))
                          ])
                      );
                      if (value == "success") {
                        setState(() {
                          _isFriend = false;
                        });
                      }
                    } else {
                      //
                      showDialog(context: context, builder: (BuildContext build) =>
                        MyNotification("是否添加 ${_detail.userName}为好友?", [
                          ElevatedButton(onPressed: () async {
                            var result = await addFriendRequest(context, widget.myId, widget.token,
                                widget.userId, meg: FRIEND_RELATION_MEG.REQ);
                            if (result != null) {
                              var result2 = await manager.addFriend(userID: widget.userId.toString(), addType: FriendTypeEnum.V2TIM_FRIEND_TYPE_BOTH,
                              addWording: "请求添加为好友", remark: _detail.userName);
                              if (result2.code == 0) {
                                Fluttertoast.showToast(msg: "请求发送成功");
                                Navigator.pop(context, "success");
                              } else {
                                Navigator.pop(context, "failed");
                              }
                            }
                          }, child: Text('确认')),
                          ElevatedButton(onPressed: () => Navigator.pop(context, "cancel"), child: Text("取消"))
                        ])
                      );
                    }
                  },
                  child: Text(_isFriend ? "删除好友" : "添加好友"),
                ),
                SizedBox(width: 16,),
                ElevatedButton(
                    onPressed: () async {
                      if (_isBlockedFriend) {
                        var result = await blockUserRequest(context, widget.myId, widget.token,
                            widget.userId, BlockedMeg.FREE);
                        if (result != null) {
                          Fluttertoast.showToast(msg: "取消拉黑成功");
                          setState(() {
                            _isBlockedFriend = false;
                          });
                        }
                      } else {
                        var result = await blockUserRequest(context, widget.myId, widget.token,
                            widget.userId, BlockedMeg.REQUEST);
                        if (result != null) {
                          Fluttertoast.showToast(msg: "拉黑成功");
                          setState(() {
                            _isBlockedFriend = true;
                          });
                        }
                      }
                    },
                    child: Text(_isBlockedFriend ? "取消拉黑" : "拉黑")
                )
              ],
              ),
              SizedBox(height: 8,),
              FutureBuilder(builder: (context, snapshot) {
                if (_isFriend) {
                  return SizedBox(
                      width: double.infinity,
                      child: ElevatedButton(onPressed: () async {
                          var conversation1 = await _conversationService.getConversation(conversationID: "c2c_${widget.userId}");
                          print('conversation now : type ${conversation1.type} id ${conversation1.userID}');
                              Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => Chat(
                                  selectedConversation: conversation1,
                                ),
                              ));
                      } , child: Text("发送信息")));
                } else {
                  return SizedBox(height: 40,);
                }
              })
            ],
          ),
        ),
      ],
        ),
    );
  }

  Widget _buildCountWidget(int count, String label, String url) {
    return Expanded(
      child: InkWell(
        onTap: () {
          Navigator.push(context, MaterialPageRoute(builder: (context) =>
              UserVoListPage(widget.token, widget.myId, url, "${_detail.userName}的$label列表", _detail.userName),
          ));
        },
        child: Column(
          children: [
            Text(
              count.toString(),
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
            Text(label),
          ],
        ),
      ),
    );
  }
}


